package org.batatasframework.support.searchable.result;

import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import org.batatasframework.support.database.spi.ResultWritable;
import org.batatasframework.support.database.sql.field.SelectFragment;
import org.batatasframework.support.database.values.FieldValueHolder;
import org.batatasframework.support.database.values.StatisticsTotal;
import org.batatasframework.support.database.values.StatisticsValue;
import org.batatasframework.support.searchable.ResultHeadInfo;
import org.batatasframework.support.searchable.SimpleHeadInfo;


public class StatisticsResultHead implements ResultHead{

	private final SelectFragment selectFragment;
	private final FieldValueHolder valueHolder;
	private final StatisticsTotal total;
	
	public StatisticsResultHead(SelectFragment selectFragment){
		this.selectFragment = selectFragment;
		this.valueHolder = selectFragment.getValueHolder();
		this.total = valueHolder.createStatistics();
	}
	
	@Override
	public boolean disabled() {
		return null == total;
	}
	
	private class StatisticsResultCell implements ResultCell{
		
		private final StatisticsValue value;
		
		public StatisticsResultCell(){
			value = total.newValue();
		}
		
		@Override
		public void read(ResultSet rs) throws Exception {
			value.read(rs);
		}

		@Override
		public void writeTo(ResultWritable resultWriter) throws Exception {
			//resultWriter.append(value);
			value.writeTo(resultWriter);
		}
	}
	
	public ResultCell newCell(){
		return new StatisticsResultCell();
	}

	@Override
	public String[] group() {
		return selectFragment.getGroup();
	}

	private List<ResultHeadInfo> itemHead;
	
	@Override
	public List<ResultHeadInfo> children() {
		if(null == itemHead){
			String[] itemNames = total.getItemNames();
			if(null != itemNames && itemNames.length > 0){
				itemHead = new ArrayList<>(itemNames.length);
				for(String itemName : itemNames){
					itemHead.add(new SimpleHeadInfo(itemName));
				}
			}else{
				itemHead = Collections.emptyList();
			}
		}
		return itemHead;
	}

	@Override
	public int compareTo(ResultHead o) {
		return ordinal() - o.ordinal();
	}

	@Override
	public int ordinal() {
		return 0;
	}

	@Override
	public String getTitle() {
		return selectFragment.getTitle();
	}

	@Override
	public int getRowspan() {
		return rowspan;
	}

	private int rowspan = 1;
	
	@Override
	public void setRowspan(int rowspan) {
		if(children().isEmpty()){
			this.rowspan = rowspan;
		}
	}
	
	@Override
	public int getColspan() {
		return children().size();
	}

	private int colspan = 1;
     
	@Override
	public void setColspan(int colspan) {
		if(!children().isEmpty()){
			this.colspan = colspan;
		} 
		
	}

}
